package utilities;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class StringUtils {

	public boolean isAnagram(String s1, String s2) {

		char[] char1 = s1.toCharArray();
		char[] char2 = s2.toCharArray();

		Arrays.sort(char1);
		Arrays.sort(char2);

		return Arrays.equals(char1, char2);
	}

	public String readFile(String path) throws IOException {
		Charset encoding = Charset.defaultCharset();
		byte[] encoded = Files.readAllBytes(Paths.get(path));
		return encoding.decode(ByteBuffer.wrap(encoded)).toString();
	}

	public long countAnagrams(String path) {
		String file = null;
		try {
			file = prepareString(path);
			String[] strings = file.split(" ");

			Arrays.sort(strings);

			Map<String, Integer> counters = new HashMap<String, Integer>();

			for (int i = 0; i < strings.length; i++) {
				String keyWord = getOrderedLetters(strings[i]);

				if (!counters.containsKey(keyWord)) {
					counters.put(keyWord, 1);

				} else {
					Integer count = counters.get(keyWord);
					counters.put(keyWord, count + 1);
				}

			}

			return counters.size();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return -1;
	}

	private String getOrderedLetters(String word) {
		char[] char1 = word.toCharArray();
		Arrays.sort(char1);
		String sorted = "";
		for (int i = 0; i < char1.length; i++) {
			sorted += char1[i];
		}
		return sorted;
	}

	private String prepareString(String path) throws IOException {
		String file;
		file = readFile(path);
		file = file.replaceAll(",", "");
		file = file.replaceAll(";", "");
		file = file.replaceAll(":", "");
		file = file.replaceAll("\"", "");
		// file = file.replaceAll("\.", "");

		return file;
	}

	public boolean isPalindromic(String str) {
		char[] chars = str.toCharArray();
		
		return isPalindromic(chars);
	}

	private boolean isPalindromic(char[] chars) {
		for (int i = 0; i < chars.length; i++) {
			char c = chars[i];
			int j = chars.length - i -1;
			char d = chars[j];
			if (c != d ) {
				return false;
			} 
			
		}	

		return true;
	}

	public String getLongestPalindrome(String str) {
		char[] chars = str.toCharArray();
		int maxLenght = 0;
		String ret = null;
		for (int i = 0; i < chars.length; i++) {
			String word = "";
			
			for (int j = i; j < chars.length; j++) {
				char c = chars[j];
				word = word + c;
				if (isPalindromic(word))  {
					if (word.length() >= maxLenght) {
						maxLenght = word.length();
						ret = word;
					}
					
				}
				
			}
			
		}
		return ret;
	}

	public int getPostion(String string, String search) {
		char[] chars = string.toCharArray();

		return -1;
	}

}
